package com.api.nosession;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.component.domain.MFilebase64;
import com.component.service.MFilebase64Service;
import com.system.common.Result;
import com.system.security.IsSecurity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URLEncoder;

/**
 * @Classname FileBase64Api
 * @Description TODO
 * @Date 2023/11/5 17:16
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@IsSecurity(isSecurity = false)
@RestController
@RequestMapping("filebase64")
public class FileBase64Api {

    @Autowired
    private MFilebase64Service mFilebase64Service;

    @PostMapping("upload")
    public JSONObject uploadFile(MultipartFile file){
        mFilebase64Service.uploadFile(file);
        return Result.successInfo("上传成功");
    }

    @PostMapping("uploadimage")
    public JSONObject uploadImage(@RequestParam("editormd-image-file") MultipartFile file){
        MFilebase64 mFilebase64=mFilebase64Service.uploadFile(file);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("success",true);
        jsonObject.put("message","上传成功");
        jsonObject.put("imageUrl","/filebase64/getfile?id="+mFilebase64.getId());
        return jsonObject;
    }

    @GetMapping("getfile")
    public void getFile(@RequestParam("id") Serializable id, HttpServletResponse response) throws IOException {
        MFilebase64 mFilebase64=mFilebase64Service.getById(id);
        if(mFilebase64!=null){

            String fileName = URLEncoder.encode(mFilebase64.getFilename(), "UTF-8");
            response.setContentType(mFilebase64.getFiletype());
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("ETag", fileName);
            response.addHeader("Content-Disposition", "form-data ; filename=" + fileName );
            response.setHeader("Last-Modified",mFilebase64.getCreateTime().toString());

           byte[] bytes=mFilebase64Service.fileBase64ToByte(mFilebase64);
           Integer len=bytes.length;
            //设置此次相应返回的数据长度
            response.setContentLength(len);
            //获取响应的输出流
            OutputStream outputStream = response.getOutputStream();
            // 将这1MB的视频流响应给客户端
            outputStream.write(bytes, 0, len);
            outputStream.close();
        }
    }


}
